<template>
  <div class="track-pool">
    <div v-if="showLoading" class="box-center">
      <atom-loading />
    </div>
    <template v-else>
      <div v-if="hasTrackPool" class="list">
        <div class="selected-pool">
          <!-- 日期 -->
          <div :class="`calendar ${remindDateArr.length ? 'has-renewal' : ''}`" v-if="showDatePick">
            <atom-sticky offset-top="12.8vw">
              <atom-calendar-tab
                :value="selectedDate"
                @input="changeDefaultDate"
                :max-date="maxDate"
                :weekFormatter="weekFormatter"
                :filter="filterDate"
                @click-calendar="show"
              >
              </atom-calendar-tab>
            </atom-sticky>
            <atom-calendar
              v-model="showCalendar"
              :max-date="maxDate"
              :default-date="selectedDate"
              :formatter="formatter"
              :effect-date-rule="filterCalendar"
              @confirm="confirm"
            >
            </atom-calendar>
          </div>
          <HoldingList
            :sortTimeType="sortTimeType"
            :activeStock="activeStock"
            :isTrackPool="true"
            :stockList="stockList"
            :cardList="cardList"
            offsetTool="29.33vw"
            offsetList="34vw"
            @modeChange="onModeChange"
            @goToShowCustom="showCustom = true"
          ></HoldingList>
          <div @click="showHolding" class="btn" v-if="dataList.length">
            持仓记录<svg-icon icon="arrow-right"></svg-icon>
          </div>
        </div>
      </div>
      <empty-pool v-else :isTrackingPool="true" @goCustomize="goCustomize"></empty-pool>
    </template>
    <atom-popup
      v-model="showCustom"
      round
      position="bottom"
      :close-on-click-overlay="false"
      get-container="body"
    >
      <TrackPoolCustom
        :needSub="needSub"
        :stepperData="stepperData"
        :pullDownData="pullDownData"
        :noticeWay="noticeWay"
        @updateNoticeWay="noticeWay = $event"
        @updateCustomData="updateCustomData"
        @show="showCustom = true"
        @hidden="showCustom = false"
        @openSubPopup="openSubPopup"
        @updateTrackPoolData="updateTrackPoolData"
        @closePopup="showCustom = false"
      />
    </atom-popup>
  </div>
</template>

<script>
import { reqTrackPoolCustomOptions, reqTrackPoolCustomStatus } from '@/apis/portfolio.api';
import dealportfolioData from '@/mixins/dealPortfolioData';
import { BASE_URL } from '@/config/pool';
import HoldingList from '@/components/servicePack/HoldingList.vue';
import EmptyPool from '@/components/detail/EmptyPool.vue';
import TrackPoolCustom from '@/components/servicePack/TrackPoolCustom.vue';
import tools from '@/lib/tools.js';

export default {
  mixins: [dealportfolioData],
  components: {
    HoldingList,
    EmptyPool,
    TrackPoolCustom,
  },
  props: {
    showTackpoolPop: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      // 是否定制了跟踪池
      hasTrackPool: false,
      // 展示自定义跟踪弹框
      showCustom: false,
      noticeWay: 'ORIGINAL',
      // 步进器数据
      stepperData: [
        {
          key: 'day_limit',
          name: '单日最大持股数',
          default: 1,
          value: 1,
          min: 1,
          max: 3,
          canInput: true,
        },
        {
          key: 'week_limit',
          name: '单周最大持股数',
          default: 1,
          value: 1,
          min: 1,
          max: 5,
          canInput: true,
        },
        {
          key: 'account_limit',
          name: '账户最大持股数',
          default: 1,
          value: 1,
          min: 1,
          max: 5,
          canInput: true,
        },
      ],
      // 下拉选择框数据
      pullDownData: [
        {
          key: 'position_limit',
          name: '单支个股仓位',
          default: '',
          value: '',
          options: [],
        },
        {
          key: 'risk_strategy',
          name: '风控策略',
          default: '',
          value: '',
          options: [],
        },
        {
          key: 'buy_strategy',
          name: '买入策略',
          default: '',
          value: '',
          options: [],
        },
        {
          key: 'sort_strategy',
          name: '买入排序策略',
          default: '',
          value: '',
          options: [],
        },
        {
          key: 'sell_strategy',
          name: '卖出条件策略',
          default: '',
          value: '',
          options: [],
        },
        {
          key: 'stop_profit_strategy',
          name: '止盈条件策略',
          default: '',
          value: '',
          options: [],
        },
        {
          key: 'stop_loss_strategy',
          name: '止损条件策略',
          default: '',
          value: '',
          options: [],
        },
      ],
      // 定制完成之后是否需要弹出订阅弹框
      needSub: false,
    };
  },
  async created() {
    this.showLoading = true;
    await this.init();
    this.showLoading = false;
  },
  methods: {
    changeDefaultDate(selectedDate) {
      this.activeStock = '';
      this.activeDate = '';
      this.selectedDate = selectedDate;
      this.getPoolData();
    },
    openSubPopup() {
      this.needSub = false;
      this.$emit('openSubPopup');
    },
    // 列表卡片模式切换
    onModeChange(mode) {
      this.currentMode = mode;
    },
    goCustomize() {
      this.needSub = true;
      this.showCustom = true;
    },
    showHolding() {
      location.href = `${BASE_URL}position?portfolio_id=${this.portfolioId}&mode=${this.currentMode}&sortTimeType=${this.sortTimeType}&title=自定义跟踪&type=servicePack`;
    },
    // 获取定制信息之后再获取跟踪池数据
    async getTrackDataStatus() {
      const statusRes = await this.getTrackPoolStatus();
      // 跟踪池id由接口返回,如果未定制跟踪池接口返回null
      if (statusRes) {
        this.hasTrackPool = true;
        this.portfolioId = statusRes.id;
        await this.getDateList();
        await this.getPoolData();
        this.getRemind();
      }
      return statusRes;
    },
    // 获取自定义跟踪池的默认配置和选项限制
    getTrackPoolOptions() {
      const params = {
        portfolio_id: window.getParam('portfolio_id'),
      };
      return reqTrackPoolCustomOptions(params)
        .then(res => {
          if (res.status_code) {
            throw new Error(
              `函数getTrackPoolOptions的接口getTrackPoolOptions返回的status_code非0。入参为：${JSON.stringify(
                params
              )}；响应值为：${JSON.stringify(res)}`
            );
          }
          return res.data;
        })
        .catch(err => {
          tools.errorReport({
            name: `TrackPool.vue的getTrackPoolOptions方法错误。${err.name}`,
            message: `入参为${JSON.stringify(params)}。${err.message}`,
            stack: err.stack,
          });
        });
    },
    // 获取自定义跟踪池的当前配置
    getTrackPoolStatus() {
      const params = {
        portfolio_id: window.getParam('portfolio_id'),
      };
      return reqTrackPoolCustomStatus(params)
        .then(res => {
          if (res.status_code) {
            throw new Error(
              `函数getTrackPoolStatus的接口reqTrackPoolCustomStatus返回的status_code非0。入参为：${JSON.stringify(
                params
              )}；响应值为：${JSON.stringify(res)}`
            );
          }
          return res.data;
        })
        .catch(err => {
          tools.errorReport({
            name: `TrackPool.vue的getTrackPoolStatus方法错误。${err.name}`,
            message: `入参为${JSON.stringify(params)}。${err.message}`,
            stack: err.stack,
          });
        });
    },
    setOptions(data) {
      this.stepperData.forEach(item => {
        const target = data?.[item.key];
        if (target) {
          item.default = target.default || '';
          item.min = target.min;
          item.max = target.max;
        }
      });
      this.pullDownData.forEach(item => {
        item.options = data?.[item.key] || [];
        item.default = item.options?.[0]?.id || '';
      });
    },
    setStatus(data) {
      this.noticeWay = data?.subscribe_type || this.noticeWay;
      this.stepperData.forEach(item => {
        let value = data?.[item.key] || item.default;
        // 防止后台配置的范围不在原先预设的范围
        if (value < item.min || value > item.max) {
          value = item.min;
        }
        item.value = value;
      });
      this.pullDownData.forEach(item => {
        let value = data?.strategy_info?.[item.key]?.id || item.default;
        if (Array.isArray(item.options) && !item.options.find(i=>i.id===value)) {
          value = item.options?.[0]?.id || '';
        }
        item.value = value;
      });
    },
    // 特殊处理 单支个股仓位 原因：积重难返，本项目是用了已上线的接口，之前后台配置的时候理应将其配置成选项类型，但是配成步进器类型。如果要修改必须要后台修改，然后pc端将原先的特殊处理去除。
    handlePositionLimitData(statusRes, optRes) {
      const position_limit = statusRes?.position_limit;
      const {
        position_limit: { default: defaultValue, min, max },
      } = optRes;
      this.pullDownData.forEach(item => {
        if (item.key === 'position_limit') {
          item.default = defaultValue;
          item.value = position_limit ? `${position_limit}%` : `${defaultValue}%`;
          item.options = [];
          const NUM10 = 10;
          for (let i = min; i <= max; i++) {
            if (i % NUM10 === 0) {
              item.options.push({ id: `${i}%`, name: `${i}%` });
            }
          }
        }
      });
    },
    async init() {
      try {
        // 并行执行 getTrackDataStatus 和 getTrackPoolOptions
        const [statusRes, optRes] = await Promise.all([
          this.getTrackDataStatus(),
          this.getTrackPoolOptions(),
        ]);
        // 此处无需判断statusRes, optRes为underfined情况，在setOptions，setStatus函数中去判断，并且同步完成初始化。catch只处理数据类型异常的情况
        this.setOptions(optRes);
        this.setStatus(statusRes);
        this.handlePositionLimitData(statusRes, optRes);
      } catch (err) {
        tools.errorReport({
          name: `TrackPool.vue的init方法错误。${err.name}`,
          message: err.message,
          stack: err.stack,
        });
      }
    },
    // 修改定制参数
    updateCustomData({ key, value }) {
      [...this.stepperData, ...this.pullDownData].forEach(item => {
        if (item.key === key) {
          item.value = value;
        }
      });
    },
    // 更新股池和定制
    updateTrackPoolData() {
      this.getTrackDataStatus()
        .then(statusRes => {
          this.setStatus(statusRes);
        })
        .catch(err => {
          tools.errorReport({
            name: `TrackPool.vue的updateTrackPoolData方法错误。${err.name}`,
            message: err.message,
            stack: err.stack,
          });
        });
    },
  },
  watch: {
    showTackpoolPop(val) {
      if (val) {
        this.goCustomize();
        this.$emit('hasShow');
      }
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.renewal-day .atom-calendar__top-info {
  color: #ff2436;
}
/deep/.renewal-day .atom-calendar__selected-day .atom-calendar__top-info {
  color: #fff;
}
.has-renewal /deep/.atom-calendar-tab__icon-wrapper {
  position: relative;
  &::before {
    position: absolute;
    .bg-mixins;
    content: '';
    background-image: url('../../assets/images/renewal.png');
    width: 26px;
    height: 14px;
    z-index: 11;
    right: -10px;
  }
}
.track-pool {
  box-sizing: border-box;
  min-height: 326px;
}
.list {
  min-height: 326px;
  height: auto;
  position: relative;
}

.box-center {
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.atom-calendar-tab {
  width: 100%;
}

.btn {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  line-height: 18px;
  color: var(--text-3);
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
}
</style>
